package pub.com.fengbo.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.upload.FormFile;

/**
 * 文件操作工具类
 * 
 * @author fengbo
 * @modify by wangzh date:2010-4-13 content:add synchronized for method
 */
public class FileUtil implements Serializable {
	/**
	 * 创建文件
	 * 
	 * @author fengbo
	 * @param filePath
	 * @return
	 */
	public static synchronized java.io.File createFile(String filePath) {
		try {
			java.io.File f = new java.io.File(filePath);
			if (!f.exists()) {
				f.createNewFile();
			}
			return f;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 创建目录
	 * 
	 * @param filePath
	 * @return
	 */
	public static synchronized boolean createMkdir(String mkdirPath) {
		try {
			java.io.File f = new java.io.File(mkdirPath);
			if (!f.exists()) {
				return f.mkdirs();
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 删除文件
	 * 
	 * @author fengbo
	 * @param filePath
	 * @return
	 */
	public static synchronized int delFile(String filePath) {
		try {
			java.io.File f = new java.io.File(filePath);
			if (f.exists()) {
				f.delete();
				return 1;
			} else {
				return 1;
			}
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 获得文件中的内容
	 * 
	 * @param filePath
	 * @return
	 */
	public static String readFile(java.io.File file) {
		StringBuffer sb = new StringBuffer();
		String str = "";
		try {
			FileReader fr = new java.io.FileReader(file);
			java.io.BufferedReader red = new java.io.BufferedReader(fr);
			while ((str = red.readLine()) != null) {
				sb.append(str + "\n");
			}
			red.close();
			fr.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return sb.toString();
	}

	/**
	 * 写入文件
	 * 
	 * @param file
	 * @param writeStr
	 * @return
	 * @modify by wangzc . date:2010-4-13 add return values;
	 */
	public static synchronized int writeFile(java.io.File file, String writeStr) {
		try {
			java.io.FileOutputStream outStream = new java.io.FileOutputStream(
					file);
			outStream.write(writeStr.getBytes());
			outStream.flush();
			outStream.close();
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}

	}

	/**
	 * 以追加方式写入文件
	 * 
	 * @param file
	 * @param writeStr
	 * @return
	 */
	public static synchronized int writeFileAdd(java.io.File file,
			String writeStr) {
		try {
			FileWriter fw = new FileWriter(file, true);
			fw.write(writeStr);
			fw.flush();
			fw.close();
			// java.io.FileOutputStream outStream = new
			// java.io.FileOutputStream(file);
			// outStream.write(writeStr.getBytes());
		} catch (Exception e) {

			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 给文件加锁
	 * 
	 * @author fengbo
	 * @param file
	 * @return
	 */
	public static FileLock lockFie(java.io.File file) {
		try {
			RandomAccessFile raf = new RandomAccessFile(file, "rw"); // r ,rw
			// ,rwd
			// 三个可选参数
			FileChannel fc = raf.getChannel();
			FileLock fl = fc.tryLock();
			return fl;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 释放文件锁
	 * 
	 * @param fl
	 */
	public static void freeLock(FileLock fl) {
		try {
			if (null != fl) {
				fl.release();
			}
		} catch (Exception e) {

		}
	}

	/**
	 * 文件上传
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public static boolean uploadfile(FormFile myFile, String filepath) {
		if (myFile == null) {
			System.out.println("上传文件为空。。。");
			return false;
		}
		try {
			FileUtil.createFile(filepath + myFile.getFileName());
			FileOutputStream fos = new FileOutputStream(filepath
					+ myFile.getFileName());
			fos.write(myFile.getFileData());
			fos.flush();
			fos.close();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 文件下载
	 * 
	 * @param request
	 * @param response
	 * @param path
	 *            文件绝对路径 /tmp/tool.exe
	 * @return
	 */
	public static boolean downloadFile(HttpServletRequest request,
			HttpServletResponse response, String path) {
		String filename = "";
		String fileminitype = "text/plain";
		try {
			java.io.File f = new java.io.File(path);
			if (f == null) {
				System.out.println("file 为空");
				return false;
			}
			filename = f.getName();
			System.out.println("filename =============" + filename);
			response.setContentType(fileminitype);
			response.setHeader("Location", filename);
			response.setHeader("Content-Disposition", "attachment; filename="
					+ filename);
			OutputStream outputStream = response.getOutputStream();
			InputStream inputStream = new FileInputStream(f);
			byte[] buffer = new byte[1024];
			int i = -1;
			while ((i = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, i);
			}
			outputStream.flush();
			outputStream.close();
			inputStream.close();
			outputStream = null;
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param filePath
	 * @return
	 */
	public static boolean checkFileEx(String filePath) {
		try {
			java.io.File f = new java.io.File(filePath);
			return f.exists();
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * @author fengbo 获得指定配置文件的KEY
	 * @return
	 * @throws Exception
	 */
	public static String[] getPropertiesKeys(String filePath) throws Exception {
		java.util.Properties p = new Properties();
		File file = FileUtil.createFile(filePath);
		p.load(new FileInputStream(file));
		return (String[]) p.keySet().toArray();

	}


	/**
	 * 递归删除 目录下的所有目录 和文件
	 * @param filepath
	 */
	public static void delDir(String filepath) {   
		File f = new File(filepath);// 定义文件路径
		if(f.exists() && f.isDirectory()){// 判断是文件还是目录
			if(f.listFiles().length==0){// 若目录下没有文件则直接删除
				f.delete();   
			}else{// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[]=f.listFiles();   
				int i =f.listFiles().length;   
				for(int j=0;j<i;j++){   
					 if(delFile[j].isDirectory()){   
						 delDir(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					 }
					 delFile[j].delete();
				 }
			 }   
			  
		}       
	}
	public static void main(String[] args) {
	
	
		 FileUtil fu = new FileUtil();
		 boolean createmkdir =
		 fu.createMkdir("D:/usr/local/centreon/filesGeneration/nagiosCFG/"+2);
		 if(createmkdir){
		 java.io.File file =
		 FileUtil.createFile("D:/usr/local/centreon/filesGeneration/nagiosCFG/"+2+"/ssmtp.conf");
		 StringBuffer sb = new StringBuffer();
		 sb.append("hostname=ebondservice@126.com \n");
		 sb.append("AuthUser=ebondservice@126.com \n");
		 sb.append("AuthPass=djpf8888 \n");
		 sb.append("mailhub=smtp.126.com \n");
		 FileUtil.writeFile(file, sb.toString());//写入文件
					
					
		 // FileUtil.writeFileAdd(file, "AuthUser=ebondservice@126.com		 \n");//写入文件
		 // FileUtil.writeFileAdd(file, "AuthPass=djpf8888 \n");//写入文件
		 // FileUtil.writeFileAdd(file, "mailhub=smtp.126.com \n");//写入文件
		 String str = fu.readFile(file);
		 String[] infos = str.split("\n");
		 for(String s:infos){
		 System.out.println(s);
		 }
		 //System.out.println("=="+str);
		 }

	}

}
